import { DBType } from "model/siteAnalysis.model";

declare let window: any;

// 初始化任务列表表
// 主键id            id                 varchar(32)
// 当前url           url                varchar(256)
// 用户名            login_name          varchar(20)
// 创建时间          creater_date       varchar(20)
// 日志类型          log_type           int 0登录 1页面访问
// 数量              count              int 次数
// 是否上传          is_upload          int 0未上传 1已上传
export const INIT_LOG_TABLE_WEBSQL = (DB): Promise<any> => {
    return new Promise((resolve, reject) => {
        if (!DB) {
            reject(' DB null');
        } else {
            DB.transaction(tx => {
                tx.executeSql("create table if not exists LOG_TABLE(id varchar(32),url varchar(256), login_name varchar(20), creater_date varchar(20), log_type int, count int, is_upload int)", [], (ctx, result) => {
                    resolve(result);
                }, (err) => {
                    console.log('INIT_LOG_TABLE 失败');
                    reject(err);
                });
            });
        }
    });
}

export const crudFromTable = (DB, sqlstr: string): Promise<any> => {
    return new Promise((resolve, reject) => {
        if (!DB) {
            reject(' DB null');
        }
        DB.transaction(tx => {
            tx.executeSql(`${sqlstr}`, [], (ctx, result) => {
                // console.log(`crudFromTable ${sqlstr}`);
                // console.dir(result)
                resolve(result);
            }, (ctx, error) => {
                console.log(`select table  error`);
                console.dir(error);
                reject(error)
            });
        });
    })
}


export const DROP_TABLE = (DB, tablename?: string): Promise<any> => {
    return new Promise((resolve, reject) => {
        if (!DB) {
            reject(' DB null');
        }
        DB.transaction(tx => {
            tx.executeSql(`drop table ${tablename}`, [], (ctx, result) => {
                console.log(`drop table ${tablename} success`);
                resolve(result);
            }, (ctx, error) => {
                console.log(`drop table ${tablename} error`);
                reject(error)
            });
        });
    });
}

// 获取某个表的总条目
export const getTotalCount = (DB, tableName: string) => {
    return new Promise((resolve, reject) => {
        crudFromTable(DB, `SELECT COUNT(*) FROM JOB${tableName}`).then((result) => {
            resolve(result);
        }).catch(err => {
            reject(err);
        })
    });
}
